﻿namespace FluentMvc.Validations
{
    using System.Collections;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using Fasterflect;

    public class EqualToValidator : FluentValidator, IClientValidatable
    {
        public string OtherPropertyName { get; set; }
        public override bool Validate(FluentValidationContext context)
        {
            return Comparer.Default.Compare(context.Model.GetPropertyValue(OtherPropertyName), context.Value) == 0;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var equalsRule = new ModelClientValidationRule
                                                {
                                                    ValidationType = "equalto",
                                                    ErrorMessage = ErrorMessage
                                                };
            equalsRule.ValidationParameters.Add("other", OtherPropertyName);
            return new List<ModelClientValidationRule> {equalsRule};
        }
    }
}